import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import '../../resources/images.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../config/kq_global.dart';
import '../../resources/kq_images.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 多选组件
///
/// [ItemType.checkbox]
///
/// 结合 KqFormEntity 使用
///
/// @author 周卓
///
class KqCheckBoxItemView extends StatefulWidget {
  final KqFormEntity entity;

  /// 多选组件多选点击回调
  final Function(KqFormEntity entity, List<CheckBoxData> checkboxData)?
      onCheckBoxChanged;

  /// [KqCheckBoxItemView]即将全部取消拦截，有时候需要至少选择一个，且需要提示用户，如果return false，代表不拦截，return true，代表拦截
  final bool Function()? willUnCheckAll;

  /// 选择控件点击回调
  final Function(KqFormEntity entity)? onTap;

  const KqCheckBoxItemView(
      {Key? key, required this.entity, this.onTap, this.onCheckBoxChanged, this.willUnCheckAll})
      : super(key: key);

  @override
  KqCheckBoxItemViewState createState() => KqCheckBoxItemViewState();
}

class KqCheckBoxItemViewState extends State<KqCheckBoxItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;

    updateValueForSubmit();

    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }


  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY =
          scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    var bgColor = widget.entity.backgroundColor ?? KqThemeColors.bgDialog;
    return Visibility(
      visible: widget.entity.visible,
      child: InkWell(
        onTap: () {
          TextFiledUtil.clearFocus(context);
          if (widget.entity.onTap != null) {
            widget.entity.onTap!(widget.entity);
          }
          if (widget.onTap != null) {
            widget.onTap!(widget.entity);
          }
        },
        child: Column(
          children: [
            Container(
              color: bgColor,
              padding: EdgeInsets.only(
                  right: (widget.entity.paddingHorizontal ??
                      KqThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      24.r) - 8.r),
              child: Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(
                        top: widget.entity.paddingVertical ??
                            KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .paddingVertical ??
                            24.r,
                        bottom: widget.entity.paddingVertical ??
                            KqThemeManager.instance
                                .getConfig()
                                .formConfig
                                .paddingVertical ??
                            24.r),
                    padding: EdgeInsets.only( right: widget.entity.titleRightMargin ?? (widget.entity.title.isNotEmpty ? 40.r : 0)),
                    child: Row(
                      children: <Widget>[
                        /// 是否必填
                        Container(
                          alignment: Alignment.centerRight,
                          width: widget.entity.paddingHorizontal ??
                              KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .paddingHorizontal ??
                              24.r,
                          padding: EdgeInsets.only(right: 2.r),
                          child: Text(
                            "∗",
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .mustInputFontSize ??
                                    24.sp,
                                color: widget.entity.mustInput &&
                                        widget.entity.isEditable()
                                    ? KqThemeColors.textRed
                                    : KqThemeColors.bgTransparent),
                          ),
                        ),

                        /// 标题
                        LimitedBox(
                          maxWidth: KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .titleMaxWidth ??
                              200.r,
                          child: Text(
                            widget.entity.title,
                            style: widget.entity.titleStyle ??
                                TextStyle(
                                    fontSize: KqThemeManager.instance
                                            .getConfig()
                                            .formConfig
                                            .titleFontSize ??
                                        16.sp,
                                    color: widget.entity.titleColor ?? KqThemeColors.text26),
                          ),
                        )
                      ],
                    ),
                  ),

                  /// 右侧按钮组
                  Expanded(
                    child: SingleChildScrollView(
                      scrollDirection: Axis.horizontal,
                      reverse: true,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: _renderRadioButtonList(),
                      ),
                    ),
                  ),
                ],
              ),
            ),

            /// 分割线
            Visibility(
                visible: !widget.entity.hideDivider, child: const KqDivider())
          ],
        ),
      ),
    );
  }

  List<Widget> _renderRadioButtonList() {
    if (!widget.entity.isEditable()) {
      //非编辑模式，只显示选中按钮的文字
      for (var data in widget.entity.checkBoxData!) {
        if (data.checked) {
          return [
            Text(
              data.item,
              style: TextStyle(
                  fontSize: KqThemeManager.instance
                          .getConfig()
                          .formConfig
                          .contentFontSize ??
                      16.sp,
                  color: KqThemeColors.text59),
            )
          ];
        }
      }
      return [];
    }
    return widget.entity.checkBoxData
            ?.map((e) => _renderRadioButtonItem(e))
            .toList() ??
        [];
  }

  // 是否只有data选中了
  bool _isOnlyChecked(CheckBoxData data) {
    if (!data.checked) {
      return false;
    }
    var list  = widget.entity.checkBoxData ?? [];
    for (var value in list) {
      if (value != data) {
        if (value.checked) {
          return false;
        }
      }
    }
    return true;
  }

  Widget _renderRadioButtonItem(CheckBoxData data) {
    return Container(
      margin: EdgeInsets.only(left: widget.entity.btnSpacing ?? 8.r),
      child: KqInkWell(
        radius: 4.r,
        onTap: () {
          if (_isOnlyChecked(data)) {
            if (widget.willUnCheckAll != null && widget.willUnCheckAll!()) {
              return;
            }
            if (widget.entity.willUnCheckAll != null && widget.entity.willUnCheckAll!()) {
              return;
            }
          }
          setState(() {
            //必填判断
            data.checked = !data.checked;
            //默认拼接itemId给valueForSubmit，逗号隔开
            updateValueForSubmit();
            //回调
            widget.entity.onCheckBoxChanged
                ?.call(widget.entity, widget.entity.checkBoxData!);
            widget.onCheckBoxChanged
                ?.call(widget.entity, widget.entity.checkBoxData!);
          });
        },
        borderWidth: 0,
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 8.r, vertical: 8.r),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              Image.asset(
                getImgPath(data, data.checked),
                width: 26.r,
                height: 26.r,
                fit: BoxFit.contain,
                color: data.checked ? KqThemeManager.getCommonConfig().mainColor : null,
                package: getPackageName(
                    data, data.checked),
              ),
              Container(
                margin: EdgeInsets.only(left: 12.r),
                child: Text(
                  data.item,
                  style: TextStyle(
                      fontSize: KqThemeManager.instance
                              .getConfig()
                              .formConfig
                              .contentFontSize ??
                          24.sp,
                      color: KqThemeColors.text59),
                ),
              )
            ],
          ),
        ),
      ),
    );
  }

  String? getPackageName(CheckBoxData data, bool chosen) {
    return chosen
        ? (data.checkedImgPath != null ? null : KqGlobal.packageName)
        : (data.unCheckedImgPath != null ? null : KqGlobal.packageName);
  }

  /// 获取图片
  String getImgPath(CheckBoxData data, bool chosen) {
    return chosen
        ? (data.checkedImgPath ?? Images.commonIcCheckboxesSelectedEnabledCircle)
        : (data.unCheckedImgPath ?? Images.commonIcCheckboxesUnselectedEnabledCircle);
  }

  /// 拼接Value值
  void updateValueForSubmit() {
    if (widget.entity.checkBoxData == null) {
      return;
    }
    var ids = '';
    for (var value in widget.entity.checkBoxData!) {
      if (value.checked) {
        if (ids.isEmpty) {
          ids = value.itemId;
        } else {
          ids = '$ids,${value.itemId}';
        }
      }
    }
    widget.entity.valueForSubmit = ids;
  }
}

/// 单选数据
class CheckBoxData {
  /// 显示名字
  String item;

  /// 选择后用户提交id
  String itemId;

  /// 是否选中
  bool checked;

  /// 选中的图片
  String? checkedImgPath;

  /// 未选中的图片
  String? unCheckedImgPath;

  /// 图片的包名，如果是组件库里的图片，要用[KqGlobal.packageName]
  String? package;

  CheckBoxData(
      {required this.item,
      required this.itemId,
      this.checked = false,
      this.checkedImgPath,
      this.unCheckedImgPath,
      this.package});

  @override
  String toString() {
    return 'CheckBoxData{item: $item, itemId: $itemId, checked: $checked, checkedImgPath: $checkedImgPath, unCheckedImgPath: $unCheckedImgPath, package: $package}';
  }
}
